<?php

namespace App\Hydrators;

use App\Exceptions\API\ValidationFailed;
use App\Models\Department;
use App\Models\Teambition;
use App\Models\User;
use Dingo\Api\Exception\ValidationHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;


class ManagementHydrator extends Hydrator
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return array
     */
    public function getCreateRules()
    {
        return [

        ];
    }

    /**
     * @return array
     */
    public function getUpdateRules()
    {
        return [
            'name'              => 'sometimes',
            'department_name'   => 'sometimes',
            'status'            => 'sometimes',
            'entry_date'        => 'sometimes',
            'leave_date'        => 'sometimes',
            'teambition_sign'   => 'sometimes',
        ];
    }


    /**
     * @param $incoming
     * @param User $model
     * @return User
     */
    public function hydrateForCreate($incoming, $model)
    {


    }

    /**
     * @param $incoming
     * @param User $model
     * @return User
     */
    public function hydrateForUpdate($incoming, $model)
    {
       if(isset($incoming->name)){
           $model->name = $incoming->name;
       }

       if(isset($incoming->department_name)){
           Department::findOrFail($incoming->department_name);
           $model->department_name = $incoming->department_name;
       }

       if(isset($incoming->status)){
           $model->status= $incoming->status;
       }

       if(isset($incoming->entry_date)){
           $model->entry_date = $incoming->entry_date;
       }

       if(isset($incoming->leave_date)){
           $model->leave_date = $incoming->leave_date;
       }

        if(isset($incoming->teambition_sign)){
            $isUser = User::where('teambition_sign',$incoming->teambition_sign)
                ->where('id' , '!=', $model->id)
                ->get()
                ->isEmpty();
            if (!$isUser) {
                throw new ValidationFailed('teambition_sign已绑定');
            }

            $isTeambition = Teambition::where('teambition_sign',$incoming->teambition_sign)
                ->get()
                ->isEmpty();
            if ($isTeambition) {
                throw new NotFoundHttpException('teambition_sign未找到');
            }



            $model->teambition_sign = $incoming->teambition_sign;
        }

        $model->save();
        return $model;


    }
}
